package com.pxene.cjh.start;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;

import com.pxene.cjh.bean.ResponseVo;
import com.pxene.cjh.service.IDownload;
import com.pxene.cjh.service.IProcess;
import com.pxene.cjh.service.IRepositoryService;
import com.pxene.cjh.service.impl.DownloadService;
import com.pxene.cjh.service.impl.ProcessService;
import com.pxene.cjh.service.impl.RedisRepositoryService;
import com.pxene.cjh.util.LoadPropertyUtil;
import com.pxene.cjh.util.RedisUtil;
import com.pxene.dmp.common.KVUrlGenerator;

public class StartJob {

	private IProcess processService;
	private IDownload downloadService;
	private IRepositoryService repositoryService;
	private RedisUtil redisUtil=new RedisUtil();
	// 固定线程池
	private ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);

	public static void main(String[] args) {
		StartJob job = new StartJob();
		job.setProcessService(new ProcessService());
		job.setRepositoryService(new RedisRepositoryService());
		job.setDownloadService(new DownloadService());
		String date = "2016112503";
		if (args[0].equals("seeds-push")) {
			job.seedsProducer(date);
		} else if (args[0].equals("data-get")) {
			job.startJob(date);
		}
		job.newFixedThreadPool.shutdown();
	}

	private void startJob(String date) {
		while (true) {
			String url=redisUtil.poll(date);
			if (!StringUtils.isBlank(url)) {

				// 下载
				String content = downloadService.download(url);
				// 解析
				ResponseVo responseVo = processService.process(content);
				
				// 存储
				if (responseVo.getData() != null) {
					System.out.println(responseVo.getData().toString());
				}

			} else {
				System.out.println("队列空，任务完成");
				break;
			}
		}
	}

	/**
	 * 根据配置产生种子url
	 * 
	 * @throws Exception
	 */
	private void seedsProducer(final String date) {
		Map<String, String> taskMap = LoadPropertyUtil.getPropertyMap();
		for (final Entry<String, String> entry : taskMap.entrySet()) {
			newFixedThreadPool.execute(new Runnable() {
				public void run() {
					String apiName = entry.getKey();
					int taskNum = Integer.parseInt(entry.getValue());
					String uri = KVUrlGenerator.getCustUrl(apiName);
					try {
						//|不编码会报错
						String temp = uri + "?index=" + URLEncoder.encode("AA|BB", "UTF-8") + "&date=" + date;
						for (int i = 0; i < taskNum; i++) {
							String url = temp.replace("AA", String.valueOf(i)).replace("BB", String.valueOf(0));
							
							// 下载
							String content = downloadService.download(url);
							// 解析
							ResponseVo responseVo = processService.process(content);
							
							if (responseVo.getData() != null) {
								String totalStr = responseVo.getData().get("imsi") == null ? responseVo.getData().get("account") : responseVo.getData().get("imsi");
								if (totalStr.matches("\\d+")) {
									int total = Integer.parseInt(totalStr);
									System.out.println(date + "----task" + i + "------" + apiName + "-----" + total);
									for (int j = 1; j <= total; j++) {
										String dataUrl = temp.replace("AA", String.valueOf(i)).replace("BB", String.valueOf(j));
										redisUtil.add(date, dataUrl); //以时间为key,将url加入队列
									}
								}
							}
						}
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			});
		}

	}

	public IProcess getProcessService() {
		return processService;
	}

	public void setProcessService(IProcess processService) {
		this.processService = processService;
	}

	public IDownload getDownloadService() {
		return downloadService;
	}

	public void setDownloadService(IDownload downloadService) {
		this.downloadService = downloadService;
	}

	public IRepositoryService getRepositoryService() {
		return repositoryService;
	}

	public void setRepositoryService(IRepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}

	public ExecutorService getNewFixedThreadPool() {
		return newFixedThreadPool;
	}

	public void setNewFixedThreadPool(ExecutorService newFixedThreadPool) {
		this.newFixedThreadPool = newFixedThreadPool;
	}

}
